package com.threadmethod.safe;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @PackageName:com.threadmethod.safe
 * @ClassName:test01
 * @Description: 演示线程的原子性问题
 * @Author: zhangxiaoyu
 * @date 2020/11/24 15:40
 */
public class Test01 {
    
    public static void main(String[] args){
         
        //启动线程
        MyInt myInt = new MyInt();
        for(int i = 1;i<=2;i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true){
                        System.out.println(Thread.currentThread().getName()+"---"+myInt.getNum());
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }
        
    }
    
    
    static  class MyInt01{
        int num;
        public int getNum(){
            return num++;
        }
    }

    //java中提供了一个线程安全的AtomicInteger类，保证了操作的原子性

     static  class MyInt{

        AtomicInteger num = new AtomicInteger();

        public int getNum(){
            return num.getAndIncrement();
        }
    }

}
